import { createApp, h } from 'vue'
import ConfirmDialog from './vConfirm.vue'

export const vConfirm = (options) => {
  return new Promise((resolve, reject) => {
    const container = document.createElement('div')
    document.body.appendChild(container)

    const tempApp = createApp({
      render() {
        return h(ConfirmDialog, {
          title: options.title || '提示',
          message: options.message,
          cancelText: options.cancelText || '取消',
          confirmText: options.confirmText || '确定',
          closeOnClickModal: options.closeOnClickModal || false,
          showInput: options.showInput || false,
          inputPlaceholder: options.inputPlaceholder || '请输入',
          onConfirm: (inputValue) => {
            if (options.onConfirm) {
              Promise.resolve(options.onConfirm(inputValue))
                .then(() => {
                  resolve(inputValue || true)
                  tempApp.unmount()
                  container.remove()
                })
                .catch(error => {
                  reject(error)
                  tempApp.unmount()
                  container.remove()
                })
            } else {
              resolve(inputValue || true)
              tempApp.unmount()
              container.remove()
            }
          },
          onCancel: () => {
            resolve({ canceled: true })
            tempApp.unmount()
            container.remove()
          },
          onClosed: () => {
            tempApp.unmount()
            container.remove()
          }
        })
      }
    })

    tempApp.mount(container)
  })
}

export default {
  install(app) {
    app.config.globalProperties.$vConfirm = vConfirm
    app.component('ConfirmDialog', ConfirmDialog)
  }
}